<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Base
 *
 * @author wurong
 */

namespace app\common;
use think\Controller;
use think\Log;

class Base extends Controller{
    public $is_login=false; 
    public $user_id="";
    public $headimg="default.png";
    public $is_admin=false;
    public $last_sign_time;
    public $have_contest=0;
        function __construct(\think\Request $request = null) {
        parent::__construct($request);
        if(config('app_debug')==false){
            $nowurl=request()->domain();
            if($nowurl!= config('web_domain')&&config('redirct_switch')){
                $this->redirect(config('web_domain'));
            }
        }
        //header("Set-Cookie:HttpOnly;");
        ini_set("session.cookie_httponly", 1);
        isset($_SESSION) OR session_start();
        //if(request()->isMobile())
        $this->view->config('view_path','../app/web/view/pc/');
        $no_read_msg=0;
        $this->last_sign_time= time();
        if(isset($_SESSION['user_id'])&& is_string($_SESSION['user_id'])){
            $this->is_login=TRUE;
            $this->user_id=$_SESSION['user_id'];
            $user= $this->userinfo($this->user_id);
            $this->headimg=$user['head'];
            $this->assign('my_oj_coin',$user['ojcoin']);
            $condition['user_id']= $this->user_id;
            $condition['status']=1;
            $no_read_msg=db('message')->where($condition)->count();
            $this->last_sign_time=$user['sign_time'];
        }
        $uinfo=$this->userinfo($this->user_id);
        if(!empty($uinfo)&&$uinfo['power']!=''&&$uinfo['power']!=0){
            $this->is_admin=TRUE;
        }
        $this->have_contest= $this->get_contest_num();// 获取未开始和进行中比赛数量        
        // 写到前台
        $this->assign('web_url',config('web_domain'));
        $this->assign('contest_num', $this->have_contest);
        $this->assign('webfont','songti'); //临时改为默认字体
        $this->assign('headimg', $this->headimg);
        $this->assign('is_admin', $this->is_admin);
        $this->assign('login_userid', $this->user_id);
        $this->assign('readmsg',$no_read_msg);
        $tmp= @file_get_contents('../data/file/radio.txt');
        $this->assign('broadcast',$tmp);
        $this->assign('qq_login', config('qq_login_switch')?'true':null);
        $this->assign('sign_disable', time()-$this->last_sign_time > config('community.sign_time')?false:true);
    }
    private function get_contest_num(){
        $condition['end_time']=['>=', date('Y-m-d H:i:s', time())];
        $condition['defunct']='N';
        return db('contest')->where($condition)->count();
    }

    public function have_power($id){
        $power= db('users')->find($this->user_id)['power'];
        if (!is_numeric($id)) {
            return FALSE;
        }
        if (isset($power[$id])&&$power[$id] == '1') {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * 提示成功的消息,并进行跳转
     * @param type $message 显示的消息
     * @param type $jumpurl 跳转的url,请使用url函数拼
     * @param type $wait 自动跳转的时间 如果等待的时间为 -1 则不自动跳转
     */
    public function do__logout(){
        session_destroy();
        $this->success_ui('注销成功', url('web/Index/home'));
    }
    public function success_ui($message,$jumpurl="",$wait=3){
        if($jumpurl==""){
            $wait=-1;
        }
        
        $this->assign('type','success');
        $this->assign('message',$message);
        $this->assign('jumpurl',$jumpurl);
        $this->assign('wait',$wait);
        echo $this->fetch('public/msg');
        exit();
    }
    
    /**
     * 
     * @param type $message 提示的消息
     * @param type $wait 自动跳转的时间 如果等待的时间为 -1 则不自动跳转
     * 该函数是提示错误信息的,自动返回上一个url
     */
    public function error_ui($message,$wait=3){
        $this->assign('type','error');
        $this->assign('message',$message);
        $this->assign('jumpurl','');
        $this->assign('wait',$wait);
        echo $this->fetch('public/msg');
        exit();
    }
   
    /**
     * 
     * @param type $user_id
     * @return type
     * 获取用户的信息
     */
    public function userinfo($user_id){
        $condition['user_id']=$user_id;
        $res=db('users')->where($condition)->find();
        return $res?$res:false;
    }
    
    /**
     *  发送邮件的函数
     * @param type $to 收件人的 邮箱地址  比如 123@qq.com
     * @param type $title 这封邮件的标题信息
     * @param type $body  这封邮件的内容信息 (格式是html)
     * @param string $username 用户的称呼,一般是用户的id
     * @return boolean 返回值为true 代表发送成功
     * 
     */
    public function sendmail($to,$title,$body,$username)
    {
        $oj_mail_user = config('oj_mail_user');
        $oj_mail_password=config('oj_mail_password');
        $oj_mail_smtp_host=config('oj_mail_smtp_host');
        $oj_mail_port=config("oj_mail_port");
        $oj_mail_username=config('oj_mail_username');
        if($username=='') $username='nyoj-user';
        $mail = new \PHPMailer\PHPMailer\PHPMailer();       
        try 
        {
            $mail->SMTPDebug = config('mail_debug');              // 如果要调bug的话，就把这个调成1
            $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->CharSet = "UTF-8"; //这里指定字符集！ 核心代码，可以解决乱码问题 
            $mail->Encoding = "base64";
            $mail->Host = $oj_mail_smtp_host;  // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = $oj_mail_user;                 // SMTP username
            $mail->Password = $oj_mail_password;                           // SMTP password
            $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = $oj_mail_port;                                    // TCP port to connect to
            $mail->setFrom($oj_mail_user, $oj_mail_username);
            $mail->addAddress($to, "=?utf-8?B?".base64_encode($username)."?=");     // Add a recipient
            $mail->isHTML(true);                                  // Set email format to HTML
            $mail->Subject =  "=?utf-8?B?".base64_encode($title)."?=";
            $mail->Body    =$body;
            $re=$mail->send();
            if($re) return true;
            else return false;
            //  echo 'Message has been sent';
        } 
        catch (Exception $e) 
        {
            echo 'Message could not be sent.';
        // echo 'Mailer Error: ' . $mail->ErrorInfo;
        }
    }
    public function GetUserHead($uid=""){
        if($uid==''){
            $uid= $this->user_id;
        }
        $res=db('users')->find($uid);
        return $res?$res['head']:'default.png';
    }
    protected function get_char($id){
        $re=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        return $re[$id];
    }
    
    public function judge($cid) {   //判断用户是否登录或登录时session是否设置为正确的
        if(!$this->is_login){
            $this->error_ui('请先登录哦~');
        }
        $private = db('contest')->where(['contest_id' => $cid])->field('private')->select();
        if ($private[0]['private'] == 1) {
            $password = db('contest')->where(['contest_id' => $cid])->field('password')->select();
            $flag=true;
            if(isset($_SESSION['cid-'.$cid]) && $_SESSION['cid-'.$cid] == $password[0]['password'])
            {
                $flag=false;
            }
            if ($flag) {
                $this->redirect('web/contest/input_password', ['cid' => $cid]); //未登录且session未设置;
            }
        }
    }
    protected function setUserID($id){
        $_SESSION['user_id']=$id;
        $this->user_id=$id;
    }
    protected function sendmessage($uid,$msg){
        $data['user_id']=$uid;
        $data['content']=$msg;
        $data['time']=time();
        $data['status']=1;
        db('message')->insert($data);
    }
    
    protected function remove_xss($val) { //XXS 过滤函数
//        $res= str_replace('<textarea','&lt;textarea',$val);
//        $res= str_replace('</textarea','&lt;/textarea',$res);
//        $res= str_replace('<script','&lt;script',$res);
//        $res= str_replace('</script','&lt;/script',$res);
        return $val;
    }
    protected function get_contest_left_time($cid){
        if($cid==null||$cid==0) return 0;
        $info=db('contest')->find($cid);
        if(empty($info)){
            return 0;
        }
        $end_time= strtotime($info['end_time']);
        $ret= $end_time-time();
        if($ret<=0) $ret=0;
        return $ret;
    }
    
    protected function mutex_update($value = 1){
        $fp=fopen("mutex","r+");
        if(flock($fp,LOCK_EX)){
            $filesize=filesize("mutex");
            $v=0;
            if($filesize!=0){
                $v=intval(fread($fp,$filesize));
            }
            $res=intval($v + $value);
            echo "res=".$res;
            rewind($fp);
            fwrite($fp,$res);
            flock($fp,LOCK_UN);
            fclose($fp);
        }
        else {
            Log::write("mutex lock ERROR",'error');
        }
    }
    protected function mutex_get(){
        $ret=intval(file_get_contents('mutex'));
        return $ret;
    }
}